angular.module('wechat-func', [])

.constant 'inWeixin', /micromessenger/.test(navigator.userAgent.toLowerCase())

.factory 'wechatConfig', ->
    signatureUrl: '/wechat/config'
    loggerBackend: ''
    debug: false
    shareData:
        title : 'Care++'
        url   : 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe31d89dfdd9864af&redirect_uri=http%3A%2F%2Fcareplus.api.test.ostengar.com%2Fwechat%2Flogin&response_type=code&scope=snsapi_base&state=123#wechat_redirect'
        img   : 'http://p1ekzzxyu.bkt.clouddn.com/khlogo.png'
        desc  : 'Care desc！'
.service 'wechatUtil', (inWeixin,$http,wechatConfig)->
    inviteCodeFunc = (inviteCode)->
        if inviteCode != undefined
            return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe31d89dfdd9864af&redirect_uri=http%3a%2f%2fcloudschool.api.test.ostengar.com%2fcloudschool%2fwechat%2flogin%3finviteCode%3d#{inviteCode}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"
        else
            return wechatConfig.shareData.url
    jsConfig = (js_appId, js_timestamp, js_nonceStr, js_signature) ->
        console.log 'jsconfig'
        wx.config({
                debug: wechatConfig.debug,
                appId: js_appId,
                timestamp: js_timestamp,
                nonceStr: js_nonceStr,
                signature: js_signature,
                jsApiList: ['chooseWXPay', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ',
                    'onMenuShareWeibo', 'scanQRCode', 'chooseImage', 'uploadImage']
            }
        )

    jsPay = (pay_prepay_id, pay_timestamp, pay_nonceStr, pay_paySign, successCallback, failCallback, cancleCallback) ->
        wx.chooseWXPay({
                timestamp: pay_timestamp,
                nonceStr: pay_nonceStr,
                package: 'prepay_id=' + pay_prepay_id,
                signType: 'MD5',
                paySign: pay_paySign,
                success: (res) ->
                    successCallback(res)
                fail: (res) ->
                    failCallback(res)
                cancel: (res) ->
                    cancleCallback(res)
            }
        )
    jsShare = (title, link, imgUrl, desc, type = 'link', dataUrl = '') ->
        wx.onMenuShareTimeline({
                title: title
                desc:desc
                link: link
                imgUrl: imgUrl
                success: ->
                    console.log "success"
                cancel: ->
                    console.log "cancel"
            }
        )
        wx.onMenuShareAppMessage({
                title: title, # 分享标题
                desc: desc, # 分享描述
                link: link, # 分享链接
                imgUrl: imgUrl, # 分享图标
                type: type, # 分享类型,music、video或link，不填默认为link
                dataUrl: dataUrl, # 如果type是music或video，则要提供数据链接，默认为空
                success: ->
                    console.log "success"
                cancel: ->
                    console.log "cancel"
            }
        )
        wx.onMenuShareQQ({
                title: title, # 分享标题
                desc: desc, # 分享描述
                link: link, # 分享链接
                imgUrl: imgUrl, # 分享图标
                success: ->
                cancel: ->
            }
        )
        wx.onMenuShareWeibo({
                title: title, # 分享标题
                desc: desc, # 分享描述
                link: link, # 分享链接
                imgUrl: imgUrl, # 分享图标
                success: ->
                cancel: ->
            }
        )
    getLocation = (successCallback)->
        wx.getLocation {
            type: 'gcj02'
            success: (res) ->
                latitude = res.latitude
                longitude = res.longitude
                successCallback(latitude, longitude)
        }
    doConfig = (configSucess = angular.noop,configFail = angular.noop)->
        $http.post(wechatConfig.signatureUrl, {url: location.href.split('#')[0]})#请求url签名
        .success (resp) ->
            if resp.code == 0
                jsConfig(resp.message.appId, resp.message.timestamp, resp.message.nonceStr, resp.message.signature)
                configSucess()
            else
                configFail()
        .error ->
            configFail()

    syncUpload = (localIds,uploadFunc) ->
        console.log 'syncUpload'
        localId = localIds.pop()
        wx.uploadImage
            localId: localId
            isShowProgressTips: 1
            success: (res) ->
                serverId = res.serverId
                console.log serverId
                # 返回图片的服务器端ID
                #其他对serverId做处理的代码
                uploadFunc(serverId)
                if localIds.length > 0
                    syncUpload(localIds,uploadFunc)
    chooseAndUploadImage = (count,chooseFunc,uploadFunc)->
        wx.chooseImage({
            count: count
            sizeType: [ 'compressed' ]
            sourceType: [
                'album'
                'camera'
            ]
            success: (res) ->
                localIds = res.localIds
                chooseFunc(localIds)
                # 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                syncUpload(localIds,uploadFunc)
        })

    {
        doConfig:doConfig
        getLocation:getLocation
        jsShare:jsShare
        jsPay:jsPay
        jsConfig:jsConfig
        chooseAndUploadImage:chooseAndUploadImage
        getInviteUrl:inviteCodeFunc
    }





.run (wechatUtil,inWeixin,wechatConfig)->
#    if not inWeixin then return
    ele = document.createElement 'script'
    ele.src = 'http://res.wx.qq.com/open/js/jweixin-1.0.0.js'
    document.body.appendChild ele
    ele.onload = -> # 在脚本加载完成后进行配置
# 会执行config动作,并且会拦截share动作,微信\朋友圈\qq\tx微博
        wechatUtil.doConfig(
            ->
                wx.ready(
                    ->
#标题,访问链接,分享的缩略图,分享的描述
                        title = wechatConfig.shareData.title
                        url = wechatConfig.shareData.url
                        img = wechatConfig.shareData.img
                        desc = wechatConfig.shareData.desc
                        wechatUtil.jsShare(title, url, img, desc)
                        wechatUtil.getLocation(->)
                )
            ->
                null
        )
